package JTChat;


import java.util.Hashtable;

import Jt.JtContext;
import Jt.JtFactory;
import Jt.JtMessage;
import Jt.JtObject;
import Jt.JtSingleton;



public class ChatManager extends JtSingleton {


    private static final long serialVersionUID = 1L;
    public static final String JtCLASS_NAME = ChatManager.class.getName(); 
    //public static final int MAX_DESCRIPTION_SIZE = 15; 
    Hashtable chatTable = new Hashtable ();
    transient JtFactory factory = new JtFactory ();
    transient JtContext context;
   
  
    public synchronized Chat retrieveChat (String chatId) {
        Chat chat;
        
        if (chatId == null)
            return (null);
        
        chat = (Chat) chatTable.get(chatId);
        if (chat == null) {
            chat = new Chat ();
            chatTable.put(chatId, chat);
        }
        
        return (chat);
        
    }
    
    
    /**
     * Process object messages.
     * <ul>
     * </ul>
     * @param message Jt Message
     */

    public Object processMessage (Object message) {

        String msgid = null;
        JtMessage e = (JtMessage) message;
        //Object content;
        String chatId;
        Chat chat;



        if (e == null)
            return null;

        msgid = (String) e.getMsgId ();

        if (msgid == null)
            return null;


        //content = e.getMsgContent();
        context = (JtContext) e.getMsgContext();

        
        if (e.getMsgId().equals (JtObject.JtDELETE)) {
            
            chatTable.clear();            
        }

        if (context == null || context.getUserName() == null) {
            handleError ("Invalid context");
            return (null);
        }
        
        
        if (e.getMsgId().equals (Chat.JtSEND)) {
            
            chatId = (String) e.getMsgData();
            
            chat = retrieveChat (chatId);
                          

            factory.sendMessage(chat, e);
            return (null);

        }
        
        if (e.getMsgId().equals (Chat.JtRECEIVE)) {
            
            
            chatId = (String) e.getMsgData();
            
            chat = retrieveChat (chatId);            

            return (factory.sendMessage(chat, e)); 
        }
        
        if (e.getMsgId().equals (Chat.KEYBOARD_EVENT)) {
            
            
            chatId = (String) e.getMsgData();
            
            chat = retrieveChat (chatId);            

            return (factory.sendMessage(chat, e)); 
        }

        
        if (e.getMsgId().equals (Chat.CONNECT)) {
            
            
            chatId = (String) e.getMsgData();
            
            chat = retrieveChat (chatId);    

            return (factory.sendMessage(chat, e)); 
        }

        return (super.processMessage (message));


    }
 
}